import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar  进度条
import 'nprogress/nprogress.css' // progress bar style 进度条样式
import { getToken,getUname } from '@/utils/auth' // get token from cookie 从 cookie 中获取令牌
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration NProgress配置

const whiteList = ['/login','/forgetPwd'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()


  // set page title  设置页面标题
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page  如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      //判断时候配置了路由信息
      const hasRoles = store.getters.routers && store.getters.routers.length > 0

      if (hasRoles) {

        next()
      } else {
        try {

    //       const routers = await store.dispatch('user/getRoute')
		  // //异步调用获取用户的可访问路由
    //       const accessRoutes = await store.dispatch('permission/generateRoutes', routers)

    //       router.addRoutes(accessRoutes)
          // next({ ...to, replace: true })
          next()
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {   //判断是否访问的路由存在白名单中
      // in the free login whitelist, go directly 在免费登录白名单中，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

//路由守卫  在路由跳转的时候，我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数。
// *在跳转之后判断*/
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
